package com.huiruan.controller;

import com.huiruan.entity.Address;
import com.huiruan.service.AddressService;
import com.huiruan.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author CTL
 * @create 2025-05-12 18:29
 */
@RestController// 声明为Spring MVC控制器，
@RequiredArgsConstructor  // Lombok 自动生成构造器
@RequestMapping("/address") // 定义控制器的基础请求路径
@Tag(name = "收货地址管理", description = "收货地址相关接口")//swagger注解
public class AddressController {
    private final AddressService addressService;


    /**
     * 获取收货地址列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<Address>> getAddressList() {
        return Result.success(addressService.getList());
    }

    /**
     * 新增收货地址
     * @param address
     * @return
     */
    @PostMapping("add")
    @Operation(summary = "新增收货地址", description = "返回成功或失败")
    public Result add(@RequestBody Address address) {
        int count = addressService.add(address);
        if (count <= 0) {
            return Result.failed("新增收货地址失败");
        }
        return Result.success("新增成功");
    }

    /**
     * 修改收货地址
     * @param address
     * @return
     */
    @PutMapping("/update/{id}")
    public Result update(@RequestBody Address address) {
        if (address.getId() == null) {
            return Result.failed("缺少地址id");
        }
        int count = addressService.update(address);
        if (count <= 0) {
            return Result.failed("修改收货地址失败");
        }
        return Result.success("修改收货地址成功");
    }

    /**
     * 删除收货地址
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        int count = addressService.deletebyId(id);
        if (count <= 0) {
            return Result.failed("要删除的地址不存在");

        }
        return Result.success("删除成功");
    }

    /**
     * 设置默认收货地址
     * @param id
     * @return
     */
    @PostMapping("/setDefault/{id}")
    public Result setDefault(@PathVariable String id){
        return  Result.success(addressService.setDefault(id));
    }
}
